<template>
  <div class="upload-img-component">
    <el-upload
      :action="uploadCertUrl"
      accept=".png,.jpg,.jpeg,.gif,.bmp"
      :headers="headers"
      :file-list="fileList"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :before-upload="beforeUpload"
      :on-error="handleError"
      :on-remove="handleRemove"
      :on-change="handleChange"
      :on-exceed="handleExceed"
      :disabled="myFlag"
      :multiple="multiple"
      :limit="limit"
      :on-success="handSuccess"
      :class="{ hide: isHiden || myFlag }"
    >
      <i class="el-icon-plus" :class="{ noIcon: isHiden }"></i>
    </el-upload>
    <div class="images" v-viewer>
      <img :src="item.src" v-for="(item, index) in imagesSrc" :key="index" />
    </div>
  </div>
</template>
<script>
import "viewerjs/dist/viewer.css";
import Viewer from "v-viewer";
import Vue from "vue";
Vue.use(Viewer, {
  defaultOptions: {
    zIndex: 9999,
  },
});

import { url_name, BASE_URL } from "@/axios/Global";
export default {
  data() {
    return {
      // uploadCertUrl: `${BASE_URL}/${url_name}/sys-fdfs-file/uploadFile`,
      fileList: [], // 图片列表
      imagesSrc: [],
      myFlag: false,
    };
  },
  props: {
    uploadCertUrl: {
      type: String,
      default: `${BASE_URL}/${url_name}/sys-fdfs-file/uploadFile`,
    },
    // acceptList: {
    //   type: Object,
    //   default: () => {},
    // },
    // 详情传过来的图片
    uploadList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    newFileList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    disabledFlag: {
      type: Boolean,
      default: false,
    },
    limit: {
      type: Number,
      default: 10,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    litM: {
      type: Number,
      default: 5,
    },
  },
  watch: {
    disabledFlag: {
      handler(val) {
        this.myFlag = this.disabledFlag;
      },
      deep: true,
      immediate: true,
    },
    uploadList(val) {
      this.fileList = [];
      val.forEach((el) => {
        el["src"] = `${window.ImgDomainUrl}${el.path}`;
        el["fileUrl"] = `${window.ImgDomainUrl}${el.path}`;
        el["url"] = `${window.ImgDomainUrl}${el.path}`;
        this.fileList.push(el);
      });
    },
    newFileList: {
      handler(file) {
        this.imagesSrc = file.map((e) => {
          if (e.src) {
            return e;
          } else {
            return {
              ...e,
              src: e.url,
            };
          }
        });
      },
      deep: true,
    },
  },
  computed: {

    headers() {
      return {
        Authorization: `${sessionStorage.getItem("token")}`,
        Currorgcode: `${sessionStorage.getItem('deptId')}`
      };
    },
    isHiden() {
      console.log(222222)
      let flag = "";
      if (this.imagesSrc.length >= this.limit) {
        flag = true;
      } else {
        flag = false;
      }
      return flag;
    },
  },
  methods: {
    show(index) {
      const viewer = this.$el.querySelector(".images").$viewer;
      viewer.view(index);
      viewer.show();
    },
    handleChange(file, fileList) {
      if (file.status == "success") {
        this.fileList = fileList;
      }
    },
    handleRemove(file, fileList) {
      if (file.status == "ready") {
        return;
      }
      let index = 0
      let ind = 0
      if(file.hasOwnProperty('response')) {
        index = this.imagesSrc.findIndex(
          (value) => value.response && value.response.data.fileUrl == file.response.data.fileUrl
        );
        ind = this.fileList.findIndex(
          (value) => value.response && value.response.data.fileUrl == file.response.data.fileUrl
        );
      } else {
        index = this.imagesSrc.findIndex(
          (value) => value.src == file.fileUrl
        );
        ind = this.fileList.findIndex(
          (value) => value.src == file.fileUrl
        );
      }
      
      this.imagesSrc.splice(index, 1);
      this.fileList.splice(ind, 1);
      this.$emit("removeImg", file);
    },
    handlePictureCardPreview(file) {
      let index = 0
      if(file.hasOwnProperty('response')) {
        index = this.imagesSrc.findIndex(
          (value) => value.src == file.response.data.fileUrl
        );
      } else {
        index = this.imagesSrc.findIndex(
          (value) => value.src == file.fileUrl
        );
      }
      
      this.show(index);
    },
    async handSuccess(response, file, fileList) {
      // await this.$emit('update:uploadList', fileList)
      if (file.response.data) {
        let newFile = file.response.data;
        newFile["src"] = `${window.ImgDomainUrl}${newFile.path}`;
        newFile["fileUrl"] = `${window.ImgDomainUrl}${newFile.path}`;
        newFile["url"] = `${window.ImgDomainUrl}${newFile.path}`;
        this.imagesSrc.push({ ...newFile });
        this.fileList.concat(newFile);
      }
      await this.$emit("uploadImgSuccess", response);
    },
    handleError(err, file, fileList) {
      this.$message({
        type: "error",
        message: "图片上传失败，请从新上传",
      });
    },
    // 文件上传之前做文件大小校验
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < this.litM;
      if (!isLt2M) {
        this.$message.error(`上传文件大小不能超过 ${this.litM}MB!`);
      }
      // .png, .jpg, .jpeg, .gif, .bmp
      let testmsg = file.name
        .substring(file.name.lastIndexOf(".") + 1)
        .toLowerCase();
      const extension1 = testmsg === "png";
      const extension2 = testmsg === "jpg";
      const extension3 = testmsg === "jpeg";
      if (!extension1 && !extension2 && !extension3) {
        this.$message({
          type: "error",
          message: "仅限上传png,jpg,jpeg格式!",
        });
      }
      return isLt2M && (extension1 || extension2 || extension3);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 20 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    }
  },
};
</script>
<style lang="scss" scoped>
.images img {
  display: none;
}
.upload-img-component {
  // overflow: hidden;
  // height: 148px;
  .hide {
    ::v-deep .el-upload--picture-card {
      display: none;
      border: 1px dashed #c0ccda !important;
    }

    .noIcon {
      display: none;
    }
  }
}
</style>
